﻿using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Xml.Serialization;

namespace Dsl.Ped.Framework.Helpers 
{
    /// <summary>
    /// Provides methods for <see cref="object"/> hasing
    /// </summary>
    public class HashingHelper 
    {
        /// <summary>
        /// Get the hash of given object
        /// </summary>
        /// <param name="obj"><see cref="object"/> which hash we're requeting</param>
        /// <returns>Hash code of the given <see cref="object"/></returns>
        public static string GetHash(object obj) {
            var hash = "";
            try {
                //
                if (obj == null) return string.Empty;

                var ms = new MemoryStream();
                var b = new BinaryFormatter();

                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, obj);

               /* b.Serialize(ms, obj);
                hash = GetMd5Sum(ms.ToArray());*/
                return writer.ToString();

                // ms.Close();
            } catch (Exception ex) {
                throw new Exception("Cannot calculate hash of an object.", ex);
            }
        }

        /// <summary>
        /// Get the Md5 sum of the given byte buffer
        /// </summary>
        /// <param name="buffer">Byte buffer</param>
        /// <returns>Md5 sum of the given buffer</returns>
        private static string GetMd5Sum(byte[] buffer) {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(buffer);

            var sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++) {
                sb.Append(result[i].ToString("X2"));
            }

            return sb.ToString();
        }
    }
}
